<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :style="{ width: width }"
    :clearable="clearable"
    :filterable="filterable"
    :remote="remote"
    :remote-method="handleRemoteSearch"
    :loading="loading"
    :disabled="disabled"
    @change="handleChange"
    @clear="handleClear"
    @focus="handleFocus"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.label"
      :value="item.id"
    >
      {{ item.label }}
    </el-option>
  </el-select>
</template>

<script setup name="HomeownerSelector">
import { homeownersList } from "@/api/fang/common"

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: null
  },
  placeholder: {
    type: String,
    default: "请选择业主"
  },
  width: {
    type: String,
    default: "100%"
  },
  clearable: {
    type: Boolean,
    default: true
  },
  filterable: {
    type: Boolean,
    default: true
  },
  remote: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  minSearchLength: {
    type: Number,
    default: 1
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change', 'clear'])

// 响应式数据
const selectedValue = ref(props.modelValue)
const options = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal
})

// 监听内部值变化
watch(selectedValue, (newVal) => {
  emit('update:modelValue', newVal)
})

// 远程搜索业主
async function handleRemoteSearch(queryString) {
  searchKeyword.value = queryString
  
  // 检查最小搜索长度
  if (queryString.length < props.minSearchLength) {
    options.value = []
    return
  }
  
  if (queryString !== '') {
    loading.value = true
    try {
      const response = await homeownersList({ searchName: queryString })
      options.value = (response.rows || []).map(item => ({
        id: item.id,
        label: item.name || item.label
      }))
    } catch (error) {
      console.error('搜索业主失败:', error)
      options.value = []
    } finally {
      loading.value = false
    }
  } else {
    options.value = []
  }
}

// 选择变化处理
function handleChange(value) {
  const selectedOption = options.value.find(item => item.id === value)
  emit('change', value, selectedOption)
}

// 清空处理
function handleClear() {
  emit('clear')
}

// 聚焦处理
function handleFocus() {
  // 可以添加聚焦时的逻辑
}

// 暴露方法给父组件
defineExpose({
  clear: () => {
    selectedValue.value = null
    options.value = []
    searchKeyword.value = ''
  },
  focus: () => {
    // 可以添加聚焦逻辑
  },
  getSelectedOption: () => {
    return options.value.find(item => item.id === selectedValue.value)
  }
})
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>

